package com.qa.dom.util;

import net.sf.json.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class NTESUtils {

    //接口地址
    private static final String SENDMSG_URL="https://api.netease.im/sms/sendcode.action";//发送验证码的请求路径URL
    private static final String VERIFYCODE_URL="https://api.netease.im/sms/verifycode.action";//验证验证码
    private static final String CREATEACCID_URL="https://api.netease.im/nimserver/user/create.action";//创建云信id
    private static final String REFRESHTOKEN_URL="https://api.netease.im/nimserver/user/refreshToken.action";//更新并获取token
    private static final String UPDATEUINFO_URL="https://api.netease.im/nimserver/user/updateUinfo.action";//更新用户名片
    private static final String CREATECHATROOM_URL="https://api.netease.im/nimserver/chatroom/create.action";//创建聊天室
    private static final String REQUESTADDR_URL="https://api.netease.im/nimserver/chatroom/requestAddr.action";//请求聊天室地址
    private static final String GETCHATROOM_URL="https://api.netease.im/nimserver/chatroom/get.action";//查询聊天室信息
    private static final String CLOSECHATROOM_URL="https://api.netease.im/nimserver/chatroom/toggleCloseStat.action";//关闭聊天室
    private static final String SENDATTACHMSG_URL="https://api.netease.im/nimserver/msg/sendMsg.action";//发送系统消息(自己服务器创建的一个系统账号)
    private static final String PUSHMSG_URL="https://api.netease.im/nimserver/msg/sendAttachMsg.action";//推送消息(ios点赞评论用到)
    private static final String QUNFAMSG_URL="https://api.netease.im/nimserver/msg/sendBatchMsg.action";//群发信息
    private static final String QUERYUSERCHATGROUP_URL="https://api.netease.im/nimserver/team/joinTeams.action";//获取用户加入的群组

    public static final String APP_KEY="797ab5731ee0af0e30ebad330edadf8e";//网易云信分配的账号
    public static final String APP_SECRET="650e41d718e5";//网易云信分配的密钥

    private static final String NONCE=StringUtils.get6RandomNumStr();//随机数
    public static final String APP_ADMIN = "t17621378525t";//云信账号

    /**
     * 发短信
     * @param phone 手机号
     * @param msgid 短信模板id
     *
     */
    public static Boolean sendMsg(String phone,String msgid) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(SENDMSG_URL);
        try {

            String curTime=String.valueOf((new Date().getTime()/1000L));
            String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime);

            //设置请求的header
            post.addHeader("AppKey",APP_KEY);
            post.addHeader("Nonce",NONCE);
            post.addHeader("CurTime",curTime);
            post.addHeader("CheckSum",checkSum);
            post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

            //设置请求参数
            List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("mobile",phone));
            nameValuePairs.add(new BasicNameValuePair("templateid",msgid));

            post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));

            //执行请求
            HttpResponse response=httpclient.execute(post);
            String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");

            //判断是否发送成功，发送成功返回true
            String code= JSONObject.fromObject(responseEntity).optString("code");
            System.out.println(code);
            if (code.equals("200")){
                //return JSONObject.fromObject(responseEntity).optString("obj");//返回验证码
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }finally{
            post.releaseConnection();
            try {
                httpclient.getConnectionManager().shutdown();
            } catch (Exception e) {
                System.out.println("http连接关闭失败");
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送系统通知(点对点)
     * @param accid 云信账号
     *
     */
    public static Boolean sendSysMsg(String accid,String content,String msgtype) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(SENDATTACHMSG_URL);
        try {

            String curTime=String.valueOf((new Date().getTime()/1000L));
            String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime);

            //设置请求的header
            post.addHeader("AppKey",APP_KEY);
            post.addHeader("Nonce",NONCE);
            post.addHeader("CurTime",curTime);
            post.addHeader("CheckSum",checkSum);
            post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

            //设置请求参数
            List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("from",APP_ADMIN));
            nameValuePairs.add(new BasicNameValuePair("ope","0"));
            nameValuePairs.add(new BasicNameValuePair("to",accid));
            nameValuePairs.add(new BasicNameValuePair("type",msgtype));
            nameValuePairs.add(new BasicNameValuePair("body",content));

            post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));

            //执行请求
            HttpResponse response=httpclient.execute(post);
            String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");

            //判断是否发送成功，发送成功返回true
            String code= JSONObject.fromObject(responseEntity).optString("code");
            System.out.println(code);
            if (code.equals("200")){
                //return JSONObject.fromObject(responseEntity).optString("obj");//返回验证码
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }finally{
            post.releaseConnection();
            try {
                httpclient.getConnectionManager().shutdown();
            } catch (Exception e) {
                System.out.println("http连接关闭失败");
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送系统通知(点对点)
     *
     */
    public static Boolean qunfaMsg(String accid,String content,String msgtype) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(SENDATTACHMSG_URL);
        try {

            String curTime=String.valueOf((new Date().getTime()/1000L));
            String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime);

            //设置请求的header
            post.addHeader("AppKey",APP_KEY);
            post.addHeader("Nonce",NONCE);
            post.addHeader("CurTime",curTime);
            post.addHeader("CheckSum",checkSum);
            post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

            //设置请求参数
            List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("fromAccid",APP_ADMIN));
//	        nameValuePairs.add(new BasicNameValuePair("ope","0"));
            nameValuePairs.add(new BasicNameValuePair("toAccids",accid));
            nameValuePairs.add(new BasicNameValuePair("type",msgtype));
            nameValuePairs.add(new BasicNameValuePair("body",content));

            post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));

            //执行请求
            HttpResponse response=httpclient.execute(post);
            String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");

            //判断是否发送成功，发送成功返回true
            String code= JSONObject.fromObject(responseEntity).optString("code");
            System.out.println(code);
            if (code.equals("200")){
                //return JSONObject.fromObject(responseEntity).optString("obj");//返回验证码
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }finally{
            post.releaseConnection();
            try {
                httpclient.getConnectionManager().shutdown();
            } catch (Exception e) {
                System.out.println("http连接关闭失败");
                e.printStackTrace();
            }
        }
    }
    /**
     * 发送推送消息(自定义通知ios评论点赞（透传）时用到)
     *
     */
    public static Boolean sendPushMsg(String accid,String msg) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(PUSHMSG_URL);
        try {

            String curTime=String.valueOf((new Date().getTime()/1000L));
            String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime);

            //设置请求的header
            post.addHeader("AppKey",APP_KEY);
            post.addHeader("Nonce",NONCE);
            post.addHeader("CurTime",curTime);
            post.addHeader("CheckSum",checkSum);
            post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

            //设置请求参数
            List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("from",APP_ADMIN));
            nameValuePairs.add(new BasicNameValuePair("msgtype","0"));
            nameValuePairs.add(new BasicNameValuePair("to",accid));
            nameValuePairs.add(new BasicNameValuePair("attach",msg));

            post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));

            //执行请求
            HttpResponse response=httpclient.execute(post);
            String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");

            //判断是否发送成功，发送成功返回true
            String code= JSONObject.fromObject(responseEntity).optString("code");
            System.out.println(code);
            if (code.equals("200")){
                //return JSONObject.fromObject(responseEntity).optString("obj");//返回验证码
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }finally{
            post.releaseConnection();
            try {
                httpclient.getConnectionManager().shutdown();
            } catch (Exception e) {
                System.out.println("http连接关闭失败");
                e.printStackTrace();
            }
        }
    }



    /**
     * 验证验证码
     *
     */
    public static Boolean checkMsg(String phone,String sum) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(VERIFYCODE_URL);
        try {

            String curTime=String.valueOf((new Date().getTime()/1000L));
            String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime);

            //设置请求的header
            post.addHeader("AppKey",APP_KEY);
            post.addHeader("Nonce",NONCE);
            post.addHeader("CurTime",curTime);
            post.addHeader("CheckSum",checkSum);
            post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

            //设置请求参数
            List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("mobile",phone));
            nameValuePairs.add(new BasicNameValuePair("code",sum));

            post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));

            //执行请求
            HttpResponse response=httpclient.execute(post);
            String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");

            //判断是否发送成功，发送成功返回true
            String code= JSONObject.fromObject(responseEntity).optString("code");
            if (code.equals("200")){
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }finally{
            post.releaseConnection();
            try {
                httpclient.getConnectionManager().shutdown();
            } catch (Exception e) {
                System.out.println("http连接关闭失败");
                e.printStackTrace();
            }
        }
    }
    /**
     * 创建云信ID
     *
     */
    public static JSONObject createAccid(String accid,String name,String icon) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(CREATEACCID_URL);
        try{

            String curTime=String.valueOf((new Date().getTime()/1000L));
            String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime);

            //设置请求的header   props
            post.addHeader("AppKey",APP_KEY);
            post.addHeader("Nonce",NONCE);
            post.addHeader("CurTime",curTime);
            post.addHeader("CheckSum",checkSum);
            post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

            //设置请求参数
            List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("accid",accid));
            nameValuePairs.add(new BasicNameValuePair("name",name));
            nameValuePairs.add(new BasicNameValuePair("icon",icon));
            post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));

            //执行请求
            HttpResponse response=httpclient.execute(post);
            String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");

            //判断是否发送成功，发送成功返回info
            String code= JSONObject.fromObject(responseEntity).optString("code");
            String info= JSONObject.fromObject(responseEntity).optString("info");
            if (code.equals("200")){
                return JSONObject.fromObject(info);
            }
            return null;
        } catch (Exception e) {
            return null;
        }finally{
            post.releaseConnection();
            try {
//				httpclient.close();
                httpclient.getConnectionManager().shutdown();
            } catch (Exception e) {
                System.out.println("http连接关闭失败");
                e.printStackTrace();
            }
        }
    }
    /**
     * 更新并获取云信ID
     *
     */
    public static JSONObject refreshToken(String accid)throws IOException{
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(REFRESHTOKEN_URL);
        try{

            String curTime=String.valueOf((new Date().getTime()/1000L));
            String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime);

            //设置请求的header
            post.addHeader("AppKey",APP_KEY);
            post.addHeader("Nonce",NONCE);
            post.addHeader("CurTime",curTime);
            post.addHeader("CheckSum",checkSum);
            post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

            //设置请求参数
            List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("accid",accid));

            post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));

            //执行请求
            HttpResponse response=httpclient.execute(post);
            String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");

            //判断是否发送成功，发送成功返回info
            String code= JSONObject.fromObject(responseEntity).optString("code");
            String info= JSONObject.fromObject(responseEntity).optString("info");
            if (code.equals("200")){
                return JSONObject.fromObject(info);
            }
            return null;
        } catch (Exception e) {
            return null;
        }finally{
            post.releaseConnection();
            try {
//				httpclient.close();
                httpclient.getConnectionManager().shutdown();
            } catch (Exception e) {
                System.out.println("http连接关闭失败");
                e.printStackTrace();
            }
        }
    }
    /**
     * 更新云信用户
     *
     */
    public static Boolean updateUinfo(String accid,String type,String value)throws IOException{
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(UPDATEUINFO_URL);
        try{

            String curTime=String.valueOf((new Date().getTime()/1000L));
            String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime);

            //设置请求的header
            post.addHeader("AppKey",APP_KEY);
            post.addHeader("Nonce",NONCE);
            post.addHeader("CurTime",curTime);
            post.addHeader("CheckSum",checkSum);
            post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

            //设置请求参数
            List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("accid",accid));
            nameValuePairs.add(new BasicNameValuePair(type,value));

            post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));

            //执行请求
            HttpResponse response=httpclient.execute(post);
            String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");

            //判断是否发送成功，发送成功返回true
            String code= JSONObject.fromObject(responseEntity).optString("code");
            if (code.equals("200")){
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }finally{
            post.releaseConnection();
            try {
//				httpclient.close();
                httpclient.getConnectionManager().shutdown();
            } catch (Exception e) {
                System.out.println("http连接关闭失败");
                e.printStackTrace();
            }
        }
    }


    /**
     * 创建聊天室
     *
     */
    public static JSONObject createChatroom(String accid,String title) throws Exception{
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(CREATECHATROOM_URL);
        try{

            String curTime=String.valueOf((new Date().getTime()/1000L));
            String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime);

            //设置请求的header
            post.addHeader("AppKey",APP_KEY);
            post.addHeader("Nonce",NONCE);
            post.addHeader("CurTime",curTime);
            post.addHeader("CheckSum",checkSum);
            post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

            //设置请求参数
            List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("creator",accid));
            nameValuePairs.add(new BasicNameValuePair("name",title));

            post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));


            //执行请求
            HttpResponse response=httpclient.execute(post);
            String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");

            //判断是否发送成功，发送成功返回true
            String code= JSONObject.fromObject(responseEntity).optString("code");
            System.out.println(code);
            if (code.equals("200")){
                return JSONObject.fromObject(responseEntity);
            }
            return null;
        } catch (Exception e) {
            return null;
        }finally{
            post.releaseConnection();
            try {
//				httpclient.close();
                httpclient.getConnectionManager().shutdown();
            } catch (Exception e) {
                System.out.println("http连接关闭失败");
                e.printStackTrace();
            }
        }
    }
    /**
     * 获取聊天室信息
     *
     */
    public static JSONObject getChatroom(String roomid) throws Exception{
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(GETCHATROOM_URL);
        try{

            String curTime=String.valueOf((new Date().getTime()/1000L));
            String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime);

            //设置请求的header
            post.addHeader("AppKey",APP_KEY);
            post.addHeader("Nonce",NONCE);
            post.addHeader("CurTime",curTime);
            post.addHeader("CheckSum",checkSum);
            post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

            //设置请求参数
            List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("roomid",roomid));
            nameValuePairs.add(new BasicNameValuePair("needOnlineUserCount","true"));

            post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));


            //执行请求
            HttpResponse response=httpclient.execute(post);
            String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");

            //判断是否发送成功，发送成功返回true
            String code= JSONObject.fromObject(responseEntity).optString("code");
            System.out.println(code);
            if (code.equals("200")){
                return JSONObject.fromObject(responseEntity);
            }
            return null;
        } catch (Exception e) {
            return null;
        }finally{
            post.releaseConnection();
            try {
//				httpclient.close();
                httpclient.getConnectionManager().shutdown();
            } catch (Exception e) {
                System.out.println("http连接关闭失败");
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取聊天室信息
     *
     */
    public static JSONObject getUserChatgroup(String accid) throws Exception{
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(QUERYUSERCHATGROUP_URL);
        try{

            String curTime=String.valueOf((new Date().getTime()/1000L));
            String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime);

            //设置请求的header
            post.addHeader("AppKey",APP_KEY);
            post.addHeader("Nonce",NONCE);
            post.addHeader("CurTime",curTime);
            post.addHeader("CheckSum",checkSum);
            post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

            //设置请求参数
            List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("accid",accid));

            post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));


            //执行请求
            HttpResponse response=httpclient.execute(post);
            String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");

            //判断是否发送成功，发送成功返回true
            String code= JSONObject.fromObject(responseEntity).optString("code");
            System.out.println(code);
            if (code.equals("200")){
                return JSONObject.fromObject(responseEntity);
            }
            return null;
        } catch (Exception e) {
            return null;
        }finally{
            post.releaseConnection();
            try {
//				httpclient.close();
                httpclient.getConnectionManager().shutdown();
            } catch (Exception e) {
                System.out.println("http连接关闭失败");
                e.printStackTrace();
            }
        }
    }

    /**
     * 打开/关闭聊天室
     *
     */
    public static Boolean operateChatroom(String accid, String roomid,String status) throws Exception{
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost post = new HttpPost(CLOSECHATROOM_URL);
        try{

            String curTime=String.valueOf((new Date().getTime()/1000L));
            String checkSum=CheckSumBuilder.getCheckSum(APP_SECRET,NONCE,curTime);

            //设置请求的header
            post.addHeader("AppKey",APP_KEY);
            post.addHeader("Nonce",NONCE);
            post.addHeader("CurTime",curTime);
            post.addHeader("CheckSum",checkSum);
            post.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");

            //设置请求参数
            List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>();
            nameValuePairs.add(new BasicNameValuePair("roomid",roomid));
            nameValuePairs.add(new BasicNameValuePair("operator",accid));
            nameValuePairs.add(new BasicNameValuePair("valid",status));

            post.setEntity(new UrlEncodedFormEntity(nameValuePairs,"utf-8"));


            //执行请求
            HttpResponse response=httpclient.execute(post);
            String responseEntity= EntityUtils.toString(response.getEntity(),"utf-8");

            //判断是否发送成功，发送成功返回true
            String code= JSONObject.fromObject(responseEntity).optString("code");
            System.out.println(code);
            if (code.equals("200")){
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }finally{
            post.releaseConnection();
            try {
//				httpclient.close();
                httpclient.getConnectionManager().shutdown();
            } catch (Exception e) {
                System.out.println("http连接关闭失败");
                e.printStackTrace();
            }
        }
    }

}
